package com.rxst.msg.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import cn.hutool.core.util.StrUtil;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传工具类
 *
 * @author Ink-足迹
 * @create 2018-06-13 20:13
 **/
@Slf4j
@Component
public class UploadFileUtil {

    public static void main(String[] args) throws Exception {
        UploadFileUtil fileUtil = new UploadFileUtil();
//        fileUtil.mergeUpload("D://myworkspace//rxst-msg//image//", "D://myworkspace//rxst-msg//image//tmp//", "李四-202108261530.mp4");
        //fileUtil.split(new File("D:/myworkspace/rxst-msg/image/test/upload.zip"), "D:/myworkspace/rxst-msg/image/test/split/", "", "zip", 30 * 1024 * 1024);
        //split(new File("D:\\公司\\项目\\测审助判仪\\张三-202108261530.mp4"), "D:\\公司\\项目\\测审助判仪\\upload\\", "", "mp4", 15 * 1024 * 1024);
        //fileUtil.combine("D:/myworkspace/rxst-msg/image/test/split/", "D:/myworkspace/rxst-msg/image/test/combine/", "upload.zip");

//        Date startDate = DateUtil.lastWeek();
//        Date endDate = DateUtil.endOfWeek(startDate);
//        Date month = DateUtil.lastMonth();
//        Date startMonth = DateUtil.beginOfMonth(month);
//        Date endMonth = DateUtil.endOfMonth(month);
//        Date day = DateUtil.offsetDay(startMonth, -1);
//        System.out.println(DateUtil.formatDate(startDate));
//        System.out.println(DateUtil.formatDate(endDate));
//        System.out.println(DateUtil.formatDate(startMonth));
//        System.out.println(DateUtil.formatDate(endMonth));
//        System.out.println(DateUtil.formatDate(day));

    }


    public void mergeUpload(String path, String tmp, String name) {
        try {
            if (StrUtil.isBlank(name)) {
                return;
            }
            String tmpName = name.split("\\.")[0];
            File file = new File(tmp + tmpName);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    long size = 0;
                    // 合并文件位置
                    String filePath = DateUtil.format(DateUtil.date(), "yyyy" + File.separator + "MM") + File.separator + tmpName;
                    File partFile = new File(path + filePath);
                    if (!partFile.exists()) {
                        partFile.mkdirs();
                    }
                    // 执行文件到服务器
                    File source = new File(partFile, name);
                    // 追加模式
                    for (int i = 0; i < files.length; i++) {
                        File part = files[i];
                        String partName = part.getName();
                        String[] split = partName.split("-");
                        if (split != null && split.length > 0) {
                            size += Long.valueOf(split[1].substring(0, split[1].indexOf(".")));
                        }
                        FileOutputStream dest = new FileOutputStream(source, true);
                        FileUtils.copyFile(part, dest);
                        dest.close();
                    }
                    String duration = getDuration(source);
                    System.out.println("duration:" + duration);
                    String[] split = name.split("-");
                    Date time = null;
                    if (split != null && split.length > 1) {
                        //String str = split[1];
                        time = DateUtil.parse(split[1].substring(0, split[1].indexOf(".")), "yyyyMMddHHmm");
                        //time = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" + str.substring(6, 8) + " " + str.substring(8, 10) + ":" + str.substring(10, 12);
                    }
                    System.out.println("time:" + DateUtil.format(time, "yyyy-MM-dd HH:mm"));
                    String fileSize = formatFileSize(size);
                    System.out.println("fileSize:" + fileSize);
                    //FileUtils.deleteDirectory(file);
                }
            }
        } catch (Exception e) {
            log.error("合并文件错误", e);
        }
    }

    /**
     * 转换文件大小
     *
     * @param size
     * @return
     */
    public String formatFileSize(long size) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (size < 1024) {
            fileSizeString = df.format((double) size) + "B";
        } else if (size < 1048576) {
            fileSizeString = df.format((double) size / 1024) + "K";
        } else if (size < 1073741824) {
            fileSizeString = df.format((double) size / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) size / 1073741824) + "G";
        }
        return fileSizeString;
    }

  /*  *//**
     * 通过文件获取时长
     *
     * @param source
     * @return
     * @throws EncoderException
     */
    public String getDuration(File source) throws EncoderException {
        Encoder encoder = new Encoder();
        MultimediaInfo info = encoder.getInfo(source);
        long duration = info.getDuration();
        int hour = (int) (duration / 1000 / 3600);
        int minute = (int) (duration / 1000 / 60);
        int second = (int) (duration / 1000 % 60);

        if (hour > 0) {
            return hour + ":" + minute + ":" + second;
        }
        if (minute > 0) {
            return "00:" + minute + ":" + second;
        }
        if (second > 0) {
            return "00:00:" + second;
        }
        return "";
    }
    /**
     * 切割指定源文件
     *
     * @param srcFile   指定要切割的源文件
     * @param outputDir 指定输出目录
     * @param size      切割大小
     * @param prefix    件名前缀
     * @param suffix    文件名后缀
     * @param
     * @throws IOException 有异常时抛出，由调用者处理
     */
    public void split(File srcFile, String outputDir, String prefix, String suffix, int size) throws IOException {
        File outFile = new File(outputDir);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        try (FileInputStream inputStream = FileUtils.openInputStream(srcFile);) {
            byte[] buffer = new byte[size];
            int len = 0;
            for (int i = 0; (len = IOUtils.read(inputStream, buffer)) > 0; i++) {
                String fileName = i + "-" + len + "." + suffix;
                log.info("开始执行切割文件fileName=" + fileName);
                File temp = FileUtils.getFile(outputDir, fileName);
                FileUtils.writeByteArrayToFile(temp, buffer, 0, len);
                log.info("size:" + len);
                log.info("结束执行切割文件fileName=" + fileName);
            }
        }
    }


    /**
     * 合并文件
     *
     * @param inputDir 碎片输入目录
     * @param destDir  合并目标文件目录
     * @param destName 合并后文件名称
     * @return Map 返回需要的属性
     */
    public Map<String, Object> combine(String inputDir, String destDir, String destName) {
        Map<String, Object> result = new HashMap<>();
        File destDirFile = new File(destDir);
        if (!destDirFile.exists()) {
            destDirFile.mkdirs();
        }
        File parentDir = FileUtils.getFile(inputDir);
        String[] files = parentDir.list();
        Integer[] sort = new Integer[files.length];
        Map<Integer, String> map = new HashMap<>();
        for (int i = 0; i < files.length; i++) {
            String index = files[i].split("\\.")[0];
            if (index.contains("-")) {
                String[] split = index.split("-");
                sort[i] = Integer.valueOf(split[0]);
                map.put(Integer.valueOf(split[0]), files[i]);
            }
        }
        Arrays.sort(sort);
        try (FileOutputStream outputStream = FileUtils.openOutputStream(new File(destDir + File.separator + destName))) {
            // 按文件名排序
            assert files != null;
            long fileSize = 0;
            for (Integer index : sort) {
                log.info("遍历指定目录的文件fileName=" + map.get(index));
                String partName = map.get(index);
                String[] split = partName.split("-");
                if (split != null && split.length > 1) {
                    fileSize += Long.valueOf(split[1].substring(0, split[1].indexOf(".")));
                }
                File file = FileUtils.getFile(parentDir, map.get(index));
                byte[] data = FileUtils.readFileToByteArray(file);
                IOUtils.write(data, outputStream);
            }
            FileUtils.deleteDirectory(parentDir);
            result.put("size", fileSize);
        } catch (Exception e) {
            log.info("合并文件异常{}" + e.toString());
        }
        return result;
    }
}

